/**
 * @Author: douxuefeng
 * @Date: 2020/8/22 上午9:48
 * @File: request
 * @Desc:
 */
package go_common

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type request struct {

}

func newRequest() *request {
	return &request{}
}
var Request = newRequest()

func (c *request) Get(url string) map[string]interface{}  {
	client := &http.Client{
		Timeout: 10 * time.Second,
	}
	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	var m map[string]interface{}
	json.Unmarshal([]byte(string(result)), &m)
	return m
}
func (c *request) Post(url string, data interface{}) map[string]interface{} {
	client := &http.Client{
		Timeout: 10 * time.Second,
	}
	postData, _ := json.Marshal(data)
	req, _ := http.NewRequest("post", url, bytes.NewBuffer(postData))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	log.Println(string(result))
	var m map[string]interface{}
	json.Unmarshal(result, &m)
	return m
}

func (c *request) PostXml(url string, data interface{}) []byte {
	client := &http.Client{
		Timeout: 10 * time.Second,
	}
	postData, _ := xml.Marshal(data)
	log.Println(string(postData))
	req, _ := http.NewRequest("post", url, bytes.NewBuffer(postData))
	req.Header.Set("Content-Type", "application/xml;charset=utf-8")
	resp, _ := client.Do(req)
	result, _ := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()
	return result
}

